import { computed, SetupContext } from 'vue';

export function createNumberModelValueFactory(props: any, context: SetupContext) {
    return {
        create(propName: string) {
            return computed<string>({
                get() {
                    const originValue = props[propName];
                    const floatValue = parseFloat(originValue);
                    return Number.isNaN(floatValue) || originValue == null ? '0' : originValue;
                },
                set(value: string) {
                    const emitValue = getInputNumber(value);
                    if (emitValue != null) {
                        context.emit(`update:${propName}`, emitValue);
                    }
                },
            });
        },
    };
}

export function getInputNumber(value: string): string | null {
    let regNumber = /^[1-9]\d*\.?\d*$|^0\.\d*$/;
    let regZero = /^0\d*$/;
    if (value === '') {
        return '0';
    }
    if (regNumber.test(value)) {
        return value;
    }
    if (regZero.test(value)) {
        if (value.length > 1) {
            return value.substring(1);
        }
        return '0';
    }
    return null;
}
